package com.framework.buss.word.util;

import com.deepoove.poi.XWPFTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class ExportUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);

    public static void exportByTemplate(HttpServletResponse response, String tempName, String fileName, Map data) {
        try (OutputStream os = response.getOutputStream()) {
            // 防止上次的buffer影响
            response.resetBuffer();
            response.addHeader("Content-Disposition",
                    new String(("attachment; filename=".concat(fileName)).getBytes(), StandardCharsets.ISO_8859_1));
            response.setContentType("application/octet-stream");
            File file = ResourceUtils.getFile("classpath:template/".concat(tempName));
            XWPFTemplate template = XWPFTemplate.compile(file).render(data);
            template.writeAndClose(os);
            os.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
